package spring.validation;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * Spring Validator: 自定义校验规则
 *
 * @author ME
 * @date   2019/10/21
 */
public class PersonValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return Person.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors err) {
        ValidationUtils.rejectIfEmpty(err, "name", "name 为空");
        Person p = (Person) target;
        if (Integer.parseInt(p.getAge()) < 0) {
            err.rejectValue("age", "年龄不能为负值");
        } else if (Integer.parseInt(p.getAge()) > 110) {
            err.rejectValue("age", "年龄不能大于 110");
        }
    }
}
